package orm.utils;

import io.rong.RongCloud;
import io.rong.messages.ImgMessage;
import io.rong.messages.TxtMessage;
import io.rong.models.CodeSuccessResult;
import io.rong.models.TokenResult;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import orm.base.Ex.BaseEx;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * Created by ashin on 2017/11/28.
 */
@Component
public class ChartUtils extends BaseEx {

    static Logger logger = Logger.getLogger(ChartUtils.class);


    @Value("#{configProperties['appKey']}")
    private String appKey;

    @Value("#{configProperties['appSecret']}")
    private String appSecret;

    public TokenResult getUserToken(String realName, String userId) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        // 获取 Token 方法
        return rongCloud.user.getToken(userId, realName, "http://www.rongcloud.cn/images/logo.png");
    }

    /**
     * 发送文字信息
     *
     * @param groupIds
     * @param fromUserId
     * @param map
     * @return
     * @throws Exception
     */
    public boolean sendTxtMsg(String[] groupIds, String fromUserId, Map map) throws Exception {
        try {
            // 发送聊天室文本消息方法（一个用户向聊天室发送消息，单条消息最大 128k。每秒钟限 100 次。）
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TxtMessage messagePublishChatroomTxtMessage = new TxtMessage(map.get("betInfo").toString(), map.get("extra") == null ? "{\"info\":\"hellp\"}" : map.get("extra").toString());
            CodeSuccessResult messagePublishChatroomResult = rongCloud.message.publishChatroom(fromUserId, groupIds, messagePublishChatroomTxtMessage);
            System.out.println("publishChatroom:  " + messagePublishChatroomResult.toString());
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 发送图片信息
     *
     * @param groupIds
     * @param fromUserId
     * @param map
     * @return
     * @throws Exception
     */
    public boolean sendImgMsg(String[] groupIds, String fromUserId, Map map) throws Exception {
        try {
            // 发送聊天室文本消息方法（一个用户向聊天室发送消息，单条消息最大 128k。每秒钟限 100 次。）
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            System.err.println(map.toString());
            ImgMessage messagePublishChatroomTxtMessage = new ImgMessage(map.get("content") == null ? getImageStr(map.get("imageUri").toString()) : getImageStrLocal(map.get("content").toString()), map.get("extra") == null ? "{\"info\":\"hellp\"}" : map.get("extra").toString(), map.get("imageUri").toString());
            CodeSuccessResult messagePublishChatroomResult = rongCloud.message.publishChatroom(fromUserId, groupIds, messagePublishChatroomTxtMessage);
            System.out.println("publishChatroom:  " + messagePublishChatroomResult.toString());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @return
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     */
    public static String getImageStrLocal(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            int count = inputStream.available();
            data = new byte[count];
            int readCount = 0; // 已经成功读取的字节的个数
            while (readCount < count) {
                readCount += inputStream.read(data, readCount, count - readCount);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        Base64 encoder = new Base64();
        String imgEncode = encoder.encodeToString(data);
        String replaceImgEcode = imgEncode.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
        return replaceImgEcode;
    }

    /**
     * @return
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     */

    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            URL url = new URL(imgFile);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();
                int count = inputStream.available();
                data = new byte[count];
                int readCount = 0; // 已经成功读取的字节的个数
                while (readCount < count) {
                    readCount += inputStream.read(data, readCount, count - readCount);
                }
                inputStream.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        Base64 encoder = new Base64();
        String imgEncode = encoder.encodeToString(data);
        String replaceImgEcode = imgEncode.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
        logger.info("replaceImgEcode=" + imgEncode);
        return imgEncode;
    }


    /**
     * 发送视频信息
     *
     * @param groupIds
     * @param fromUserId
     * @return
     * @throws Exception
     */
    public boolean sendMsg(String[] groupIds, String fromUserId, Map map) throws Exception {
        try {
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            // 发送聊天室视频消息方法（一个用户向聊天室发送消息，单条消息最大 128k。每秒钟限 100 次。）
            VideoMessage videoMessage = new VideoMessage(map.get("videoUrl").toString(), map.get("issue").toString());
            CodeSuccessResult messagePublishChatroomResult = rongCloud.message.publishChatroom(fromUserId, groupIds, videoMessage);
            System.out.println("publishChatroom:  " + messagePublishChatroomResult.toString());
            return true;
        } catch (Exception e) {
            logger.error("发送失败", e);
            return false;
        }
    }

}
